import {
  ActivityIndicator,
  Dimensions,
  DimensionValue,
  FlatList,
  View,
  Text,
  RefreshControl,
} from 'react-native';
import {UserToken} from '../../../../db/models/userTokenModel';
import {userSolanaTransactionHistory} from '../../../../hooks/useSolana/useSolanaTransactionHistory';
import {useCallback, useEffect, useState} from 'react';
import {ParsedTransactionWithMeta} from '@solana/web3.js';
import TokenTxHistoryItem from './TokenTxHistoryItem';
import tw from 'twrnc';
import {
  primaryColor,
  primaryColor2,
  primaryColor3,
  secondaryBackgroundColor,
  secondaryBorderColor,
} from '../../../../theme/default';
import TokenTxFeeHistoryItem from './TokenTxFeeHistoryItem';
import {useTranslation} from 'react-i18next';

type TokenTxHisoryListProp = {
  tokenInfo?: UserToken;
  height?: DimensionValue | undefined;
};

const {width} = Dimensions.get('window');
const limit = 10;

export default function TokenTxHistoryList({
  tokenInfo,
  height,
}: Readonly<TokenTxHisoryListProp>) {
  const {
    getSOLTransferHistory,
    getSPLTokenTransferHistory,
    getSPLTransferInstruction,
    getSOLTransferInstruction,

    loading,
    beforeSignature,
    hasMore,
  } = userSolanaTransactionHistory();
  const [tansferHistoryList, setTransferHistoryList] = useState<
    (ParsedTransactionWithMeta | null)[]
  >([]);
  const [loadingMore, setLoadingMore] = useState<boolean>(false);
  const [refreshing, setRefreshing] = useState<boolean>(false);
  const {t} = useTranslation();

  const renderFooter = () => {
    if (!loadingMore) return null;

    return (
      <View
        style={{
          padding: 10,
          justifyContent: 'center',
          alignItems: 'center',
          flexDirection: 'row',
        }}>
        <ActivityIndicator size="small" color={primaryColor} />
        <Text style={{color: primaryColor2}}>Loading...</Text>
      </View>
    );
  };

  const handleLoadMore = useCallback(async () => {
    if (!hasMore) {
      return;
    }
    setLoadingMore(true);
    let txHistoryList = [];
    if (tokenInfo?.type == 'native') {
      txHistoryList = await getSOLTransferHistory(tokenInfo.owner, {
        before: beforeSignature,
        limit: limit,
      });
    } else {
      txHistoryList = await getSPLTokenTransferHistory(
        tokenInfo!.owner,
        tokenInfo!.address,
        {
          before: beforeSignature,
          limit: limit,
        },
      );
    }

    setTransferHistoryList(tansferHistoryList.concat(txHistoryList));
    setLoadingMore(false);
  }, [tansferHistoryList, beforeSignature]);

  const getTxHistory = async () => {
    let txHistoryList = [];
    if (tokenInfo?.type == 'native') {
      txHistoryList = await getSOLTransferHistory(tokenInfo.owner, {
        limit: limit,
      });
    } else {
      txHistoryList = await getSPLTokenTransferHistory(
        tokenInfo!.owner,
        tokenInfo!.address,
        {
          limit: limit,
        },
      );
    }
    setTransferHistoryList(txHistoryList);
  };

  useEffect(() => {
    getTxHistory();
  }, [tokenInfo]);

  useEffect(() => {
    if (!loading) {
      setRefreshing(false);
    }
  }, [loading]);

  const onRefresh = () => {
    setRefreshing(true);
    getTxHistory();
  };

  const renderTokenTxHistoryItem = ({
    item,
  }: {
    item: ParsedTransactionWithMeta | null;
  }) => {
    let parsedTx;
    if (tokenInfo?.type == 'native') {
      parsedTx = getSOLTransferInstruction(item!);
      if (parsedTx == undefined) {
        //
        return (
          <TokenTxFeeHistoryItem
            tokenInfo={tokenInfo!}
            txHistory={item!}
            key={item?.blockTime}></TokenTxFeeHistoryItem>
        );
      }
    } else {
      parsedTx = getSPLTransferInstruction(item!);
    }

    return (
      <TokenTxHistoryItem
        tokenInfo={tokenInfo!}
        isNative={tokenInfo?.type == 'native'}
        txHistory={item!}
        parsedTx={parsedTx}
        key={item?.blockTime}
        onPress={() => {}}></TokenTxHistoryItem>
    );
  };

  return loading && !loadingMore && !refreshing ? (
    <View
      style={{
        minHeight: 180,
        justifyContent: 'center',
        alignItems: 'center',
        maxHeight: height,
        ...tw.style('flex flex-col gap-5'),
        ...tw.style(
          `border border-[${secondaryBorderColor}] mt-[10px] p-4 rounded-xl bg-[${secondaryBackgroundColor}]`,
        ),
      }}>
      <ActivityIndicator
        size={'large'}
        color={primaryColor}></ActivityIndicator>
    </View>
  ) : tansferHistoryList.length == 0 ? (
    <View
      style={{
        minHeight: 180,
        justifyContent: 'center',
        alignItems: 'center',
        maxHeight: height,
        ...tw.style('flex flex-col gap-5'),
        ...tw.style(
          `border border-[${secondaryBorderColor}] mt-[10px] p-4 rounded-xl bg-[${secondaryBackgroundColor}]`,
        ),
      }}>
      <Text style={{fontSize: 16, color: primaryColor3}}>
        {t('noData')}+"8888888888
      </Text>
    </View>
  ) : (
    <FlatList
      showsVerticalScrollIndicator={false}
      ListHeaderComponent={<View style={{height: 0}} />}
      contentContainerStyle={{
        paddingTop: 0,
        flexGrow: 1,
      }}
      contentInset={{top: 0}}
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={onRefresh}
          colors={[primaryColor2]} // Android: Circle colors
          tintColor={primaryColor2}
        />
      }
      style={{
        maxHeight: height,
        ...tw.style('flex flex-col gap-5'),
        ...tw.style(
          `border border-[${secondaryBorderColor}] mt-[12px] pl-4 pr-4 pb-6 rounded-xl bg-[${secondaryBackgroundColor}]`,
        ),
      }}
      onEndReached={handleLoadMore}
      onEndReachedThreshold={0.1}
      ListFooterComponent={renderFooter}
      data={tansferHistoryList}
      renderItem={renderTokenTxHistoryItem}
      keyExtractor={item => item!.blockTime! + ''}></FlatList>
  );
}
